﻿using CommonTools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Result = CommonTools.Result;

namespace shop.Web.Controllers.refund
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RefundController : ControllerBase
    {
        
        readonly IFreeSql _sql;

        public RefundController(IFreeSql sql)
        {
            _sql = sql;
        }

        /// <summary> 保存退款单的物料信息 </summary>
        [HttpPost]
        public async void SaveRefundGoods([FromBody] List<List<string>> data)
        {
            if(data.Count ==0 )
            {
                return;
            }


            var batch = data[0][0];

            var list = (await _sql.Select<RefundDoc>()
                .Where(a => a.isdel == false && a.Batch == batch)
                .ToListAsync(a => new { a.Id, a.Batch, a.RowIndex, }))
                .Select(a=> new RefundDoc() { Id= a.Id, Batch= a.Batch, RowIndex= a.RowIndex})
                .ToList();


            var goodsList = ConvertGoods(data, list, batch);     //退款物料

            await DB.FSql.Insert(goodsList).ExecuteAffrowsAsync();

        }


        /// <summary> 保存退款单的主体 </summary>
        [HttpPost]
        public async Task<CommonTools.Result> SaveItems([FromBody] List<List<string>> data)
        {

            var batch = Guid.NewGuid().ToString();  

            List<RefundDoc> list = ConvertRefund(data);   //退款信息, 
            foreach (var item in list)
            {
                item.Batch = batch;
            }

            // 检查重复的, 将原先的标记删除 
            var tmp = list.Select(a => new IdTemp() { Name = a.RefundNo }).ToList();

            // 先删除物料部分
            var docs =  await DB.FSql.Select<RefundDoc>()
                .Where(a => a.isdel == false)
                .FromQuery(DB.FSql.Select<IdTemp>().WithMemory(tmp))
                .InnerJoin((a, b) => a.RefundNo == b.Name)
                .ToListAsync((a, b) => new IdTemp() { Id = a.Id });

            await DB.FSql.Select<RefundDocItem>()
                .FromQuery(DB.FSql.Select<IdTemp>().WithMemory(docs))
                .InnerJoin((a, b) => a.DocId == b.Id)
                .ToDelete()
                .ExecuteAffrowsAsync();


            await DB.FSql.Select<RefundDoc>()
                .Where(a => a.isdel == false)
                .FromQuery(DB.FSql.Select<IdTemp>().WithMemory(tmp))
                .InnerJoin((a, b) => a.RefundNo == b.Name)
                .ToUpdate()
                .Set(a => a.isdel, true)
                .ExecuteAffrowsAsync();



            // 保存
            list = await DB.FSql.Insert(list)
                .ExecuteInsertedAsync();

            return new Result(true, batch);

        }


        static List<RefundDoc> ConvertRefund(List<List<string>> data)
        {
            // 
            int plat = -1, shop = -1, no = -1, tid = -1, typeCol = -1, platSta = -1, sysSta = -1, failCol = -1, backStatusCol = -1, stageCol = -1, csCol = -1, modCol = -1, buyerCol = -1, refundAmntCol = -1, actAmnt = -1, nick = -1, reasonCol = -1, remarkCol = -1, logiName = -1, logoNo = -1, retime = -1, modifyCol = -1, crtTime = -1, success = -1, city = -1, addr = -1, userCol = -1, refuse = -1;


            int i = 0;
            foreach (var item in data[0])
            {
                if (item == "平台") plat = i;
                if (item == "店铺") shop = i;
                if (item == "退款单号") no = i;
                if (item == "原始单号") tid = i;
                if (item == "类型") typeCol = i;
                if (item == "平台状态") platSta = i;
                if (item == "系统状态") sysSta = i;
                if (item == "递交失败原因") failCol = i;
                if (item == "退款回传状态") backStatusCol = i;
                if (item == "退款阶段") stageCol = i;
                if (item == "客服介入") csCol = i;
                if (item == "交易类型") modCol = i;
                if (item == "买家支付账号") buyerCol = i;
                if (item == "申请退款金额") refundAmntCol = i;
                if (item == "实际退款金额") actAmnt = i;
                if (item == "昵称") nick = i;
                if (item == "退款原因") reasonCol = i;
                if (item == "备注") remarkCol = i;
                if (item == "物流公司") logiName = i;
                if (item == "物流单号") logoNo = i;
                if (item == "退款时间") retime = i;
                if (item == "修改时间") modifyCol = i;
                if (item == "创建时间") crtTime = i;
                if (item == "退款成功时间") success = i;
                if (item == "原始单省市区") city = i;
                if (item == "原始单地址") addr = i;
                if (item == "操作人") userCol = i;
                if (item == "拒收退款标记") refuse = i;

                i++;
            }


            var res = data
                .Skip(1)
                .Select(a => new RefundDoc()
                {
                    RowIndex= a[0].IsNull(0),
                    PlatForm = a[plat],
                    Shop = a[shop],
                    RefundNo = a[no],
                    Tid = a[tid],
                    RefundType = a[typeCol],
                    RefundStatus = a[platSta],
                    ProcessStatus = a[sysSta],
                    GiveFailReason = a[failCol],
                    BackStatus = a[backStatusCol],
                    RefundStage = a[stageCol],
                    cs_status = a[csCol],
                    guarantee_mode = a[modCol],
                    buyer = a[buyerCol],
                    RefundAmount = a[refundAmntCol].IsNull(0m),
                    ActualRefundAmount = a[actAmnt].IsNull(0m),
                    buyerNick = a[nick],
                    RefundReason = a[reasonCol],
                    Remarks = a[remarkCol],
                    logistics_name = a[logiName],
                    logistics_no = a[logoNo],
                    RefundTime = a[retime].IsNullDate(null),
                    ModifyTime = a[modifyCol].IsNullDate(null),
                    CreatedTime = a[crtTime].IsNullDate(null),
                    current_phase_timeout = a[success].IsNullDate(null),
                    OrigalCity = a[city],
                    OrigalAddr = a[addr],
                    Operator = a[userCol],
                    RefuseAccept = a[refuse],
                    isdel = false,
                     
                })
                .ToList();

            return res;

        }



        static List<RefundDocItem> ConvertGoods(List<List<string>> data, List<RefundDoc> docs, string batch)
        {
            // 
            int platform = -1, src_tids = -1, RefundStatus = -1, platform_goods_id = -1, platform_spec_id = -1, goods_no = -1, spec_no = -1, goodsName = -1, specName = -1, num = -1, price = -1, total_amount = -1, remarks = -1, modified = -1, created = -1;


            int i = 0;
            foreach (var item in data[0])
            {
                //if (item == "0") docIndex = i;
                if (item == "平台") platform = i;
                if (item == "原始子单号") src_tids = i;
                if (item == "平台状态") RefundStatus = i;
                if (item == "货品ID") platform_goods_id = i;
                if (item == "规格ID") platform_spec_id = i;
                if (item == "货品编号") goods_no = i;
                if (item == "规格码") spec_no = i;
                if (item == "货品名称") goodsName = i;
                if (item == "规格名称") specName = i;
                if (item == "数量") num = i;
                if (item == "价格") price = i;
                if (item == "总额") total_amount = i;
                if (item == "备注") remarks = i;
                if (item == "修改时间") modified = i;
                if (item == "创建时间") created = i;

                i++;
            }


            var res = data
                .Skip(1)
                .Select(a => new RefundDocItem()
                {
                    DocId = docs.FirstOrDefault(c=> c.Batch == batch && a[0] == c.RowIndex.ToString())?.Id ?? 0,
                    Batch= batch,
                    platform = a[platform],
                    src_oid = a[src_tids],
                    RefundStatus = a[RefundStatus],
                    platform_goods_id = a[platform_goods_id],
                    platform_spec_id = a[platform_spec_id],
                    goods_no = a[goods_no],
                    spec_no = a[spec_no],
                    goodsName = a[goodsName],
                    specName = a[specName],
                    num = a[num].IsNull(0m),
                    price = a[price].IsNull(0m),
                    total_amount = a[total_amount].IsNull(0m),
                    remarks = a[remarks],
                    modified = a[modified].IsNullDate(null),
                    created = a[created].IsNullDate(null),

                })
                .ToList();

            return res;

        }

    }


}
